from flask import Blueprint, jsonify, request

from application.services.system.dict_data import DictDataService
from application.utils.common import parse_id_list
from application.utils.res import json_fail, json_success, page_success

# 创建蓝图
bp = Blueprint("dict_data", __name__, url_prefix="/dict/data")


@bp.get("/list")
def get_dict_data_list():
    """
    分页获取字典数据列表
    支持条件查询：pageNum, pageSize, dictLabel, dictType, status
    """
    try:
        # 获取分页参数
        page_num = int(request.args.get("pageNum", 1))
        page_size = int(request.args.get("pageSize", 10))

        # 获取查询条件
        conditions = {
            "dictLabel": request.args.get("dictLabel"),
            "dictType": request.args.get("dictType"),
            "status": request.args.get("status"),
        }

        # 过滤空值条件
        filtered_conditions = {
            k: v for k, v in conditions.items() if v is not None and v != ""
        }

        # 调用服务获取数据
        list, total = DictDataService.get_dict_data_list(
            page_num, page_size, filtered_conditions
        )

        return page_success(list, total)
    except Exception as e:
        return json_fail(f"查询失败: {str(e)}"), 500


@bp.get("/type/<dict_type>")
def get_dict_data_by_type(dict_type):
    """
    获取字典数据列表
    """
    try:
        result = DictDataService.get_dict_data_by_type(dict_type)
        return json_success(result)
    except Exception as e:
        return json_fail(f"查询失败: {str(e)}"), 500
    



@bp.post("")
def create_dict_data():
    """ 
    创建字典数据
    """
    try:
        # 获取请求数据
        data = request.get_json()
        
        if not data:
            return json_fail("请求数据不能为空"), 400
            
        result = DictDataService.create_dict_data(data)
        return json_success(result, "创建成功", 200)
    except Exception as e:
        return json_fail(f"创建失败: {str(e)}"), 500

@bp.put("")
def update_dict_data():
    """ 
    更新字典数据
    """
    try:
        # 获取请求数据
        data = request.get_json()
        
        if not data:
            return json_fail("请求数据不能为空"), 400
        
        dict_code = data.get("dictCode")
        if not dict_code:
            return json_fail("字典ID不能为空"), 400
            
        result = DictDataService.update_dict_data(dict_code, data)
        if result:
            return json_success(result, "更新成功")
        else:
            return json_fail("产品型号不存在"), 404
    except Exception as e:
        return json_fail(f"更新失败: {str(e)}"), 500




@bp.delete("/<string:dict_code>")
def batch_delete_dict_data(dict_code):
    """
    删除绕组
    :param coil_id: 绕组ID
    """
    try:
        id_list = parse_id_list(dict_code)
        count = DictDataService.batch_delete_dict_data(id_list)
        return json_success(count, "删除成功")
       
    except Exception as e:
        return json_fail(f"删除失败: {str(e)}"), 500
